<script setup lang="ts">
definePageMeta({ layout: false });

const frm = reactive({
  email: "",
  password: "",
  captcha: "",
});

const { toast, msg } = useStatus();
const { $post } = use$fetch();
const { auth } = useAdminAuth();
const { to } = useRoute().query;

const handleSubmit = async () => {
  if (!frm.captcha) {
    toast.value = "请完成人机验证";
    return;
  }

  const { data } = await $post<LoginResp>("/auth/admin-login", { ...frm });

  if (!data.value) {
    toast.value = "登录失败，请检查网络";
    return;
  }

  msg.value = "登录成功";

  auth.value = data.value!;

  navigateTo(to ? to.toString() : "/admin");
};

const handleCaptchaVerify = (token: string) => {
  frm.captcha = token;
};
</script>

<template>
  <Dialog>
    <form
      class="flex flex-col gap-y-4"
      autocomplete="off"
      @submit.prevent="handleSubmit"
    >
      <h2 class="text-xl text-center">后台登录</h2>

      <label class="grid grid-cols-12 items-center">
        <div class="col-span-4 lg:col-span-3 tracking-[2rem]">邮箱</div>
        <div
          class="border rounded group focus-within:border-gray-300 overflow-hidden col-span-8 lg:col-span-9"
        >
          <input
            class="block w-full outline-none px-2 py-1"
            type="email"
            placeholder="请输入你的邮箱"
            v-model="frm.email"
            required
          />
        </div>
      </label>

      <label class="grid grid-cols-12 items-center">
        <div class="col-span-4 lg:col-span-3 tracking-[2rem]">密码</div>
        <div
          class="border rounded group focus-within:border-gray-300 overflow-hidden col-span-8 lg:col-span-9"
        >
          <input
            class="block w-full outline-none px-2 py-1"
            type="password"
            placeholder="请输入你的密码"
            v-model="frm.password"
            required
          />
        </div>
      </label>

      <div class="lg:grid lg:grid-cols-12 lg:items-center">
        <div class="mb-2 lg:col-span-3 lg:mb-0">人机验证</div>
        <div class="lg:col-span-9">
          <HCaptcha @verify="handleCaptchaVerify" />
        </div>
      </div>

      <div class="flex justify-end items-center gap-x-2">
        <button class="px-3 py-1.5 bg-cyan-700 text-white rounded">登录</button>
      </div>
    </form>
  </Dialog>
</template>
